package com.wenzhoujie.http;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.NameValuePair;

import com.wenzhoujie.library.utils.SDToast;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.ta.sunday.http.impl.SDAsyncHttpResponseHandler;
import com.ta.util.netstate.TANetWorkUtil;
import com.wenzhoujie.app.App;
import com.wenzhoujie.common.HttpManagerX;
import com.wenzhoujie.constant.ApkConstant;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.RequestModel.RequestDataType;
import com.wenzhoujie.proxy.RequestCallBackProxy;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.LogUtil;
import com.wenzhoujie.utils.MiGBase64;

/**
 * 接口请求类
 */
public class InterfaceServer
{

	private static final class Holder
	{
		static final InterfaceServer mInstance = new InterfaceServer();
	}

	private InterfaceServer()
	{
	}

	public static InterfaceServer getInstance()
	{
		return Holder.mInstance;
	}

	public HttpHandler<String> requestInterface(RequestModel model, RequestCallBack<String> responseListener)
	{
		return requestInterface(HttpMethod.POST, model, null, true, responseListener);
	}
	
	/**
	 * 
	 * @param httpMethod
	 *            请求方法
	 * @param model
	 *            RequestModel
	 * @param responseListener
	 *            回调监听
	 * @param httpUtils
	 *            HttpUtils对象，如果为null则用全局单例对象，不为null则用该对象
	 * @param isNeedProxy
	 *            是否需要代理
	 * @return
	 */
	public HttpHandler<String> requestInterface(HttpMethod httpMethod, RequestModel model, HttpUtils httpUtils, boolean isNeedProxy, RequestCallBack<String> responseListener)
	{
		if (TANetWorkUtil.isNetworkAvailable(App.getApplication()))
		{
			if (model != null)
			{
				RequestParams requestParams = getRequestParams(model);
				RequestCallBack<String> listener = null;
				if (isNeedProxy)
				{
					listener = getDefaultProxy(responseListener, model);
				} else
				{
					listener = responseListener;
				}
				if (httpUtils != null)
				{
					return httpUtils.send(httpMethod, ApkConstant.SERVER_API_URL, requestParams, listener);
				} else
				{
					return HttpManagerX.getHttpUtils().send(httpMethod, ApkConstant.SERVER_API_URL, requestParams, listener);
				}
			} else
			{
				return null;
			}
		} else
		{
			SDToast.showToast("网络不可用");
			responseListener.onFinish();
			return null;
		}
	}

	private RequestCallBack<String> getDefaultProxy(RequestCallBack<String> handler, RequestModel model)
	{
		return new RequestCallBackProxy(handler, model);
	}

	private RequestParams getRequestParamsNoJson(RequestModel model)
	{
		RequestParams requestParams = new RequestParams();
		Object data = model.getmData();
		if (data != null)
		{
			Map<String, Object> mapData = (Map<String, Object>) data;
			for (Entry<String, Object> entry : mapData.entrySet())
			{
				String key = (entry.getKey()) == null ? "" : (entry.getKey());
				String value = (entry.getValue()) == null ? "" : (String.valueOf(entry.getValue()));
				// if (key.equals("pwd"))
				// {
				// value = MD5.hexdigest(value);
				// }
				requestParams.addQueryStringParameter(key, value);
			}
			requestParams.addQueryStringParameter("i_type", String.valueOf(model.getmRequestDataType()));
			requestParams.addQueryStringParameter("r_type", String.valueOf(model.getmResponseDataType()));
			requestParams.addQueryStringParameter("soft_type", ApkConstant.SoftType.O2O);
			requestParams.addQueryStringParameter("dev_type", ApkConstant.DeviceType.DEVICE_ANDROID);
		}
		return requestParams;
	}

	private void printRequestUrl(RequestParams param)
	{
		if (ApkConstant.DEBUG)
		{
			StringBuilder sb = new StringBuilder(ApkConstant.SERVER_API_URL + "?");
			if (param != null)
			{
				List<NameValuePair> listParam = param.getQueryStringParams();
				for (NameValuePair nameValuePair : listParam)
				{
					sb.append("&");
					sb.append(nameValuePair.getName());
					sb.append("=");
					if ("r_type".equals(nameValuePair.getName()))
					{
						sb.append("2");
					} else
					{
						sb.append(nameValuePair.getValue());
					}
				}
			}
			LogUtil.i(sb.toString());
		}
	}

	private RequestParams getRequestParams(RequestModel model)
	{
		RequestParams requestParams = new RequestParams();
		Map<String, Object> data = model.getmData();
		Map<String, File> dataFile = model.getmDataFile();
		if (data != null)
		{
			String requestData = "";
			if (model.getmRequestDataType() == RequestDataType.BASE64)
			{
				requestData = MiGBase64.encode(JsonUtil.object2Json(data));
			} else if (model.getmRequestDataType() == RequestDataType.REQUEST)
			{
				requestData = JsonUtil.object2Json(data);
			}
			requestParams.addQueryStringParameter("requestData", requestData);
			requestParams.addQueryStringParameter("i_type", String.valueOf(model.getmRequestDataType()));
			requestParams.addQueryStringParameter("r_type", String.valueOf(model.getmResponseDataType()));
			requestParams.addQueryStringParameter("act", String.valueOf(data.get("act")));
			requestParams.addQueryStringParameter("soft_type", ApkConstant.SoftType.O2O);
			requestParams.addQueryStringParameter("dev_type", ApkConstant.DeviceType.DEVICE_ANDROID);
		}
		if (dataFile != null)
		{
			for (Entry<String, File> itemFile : dataFile.entrySet())
			{
				if (itemFile != null)
				{
					requestParams.addBodyParameter(itemFile.getKey(), itemFile.getValue());
				}
			}
		}
		printRequestUrl(requestParams);
		return requestParams;
	}

}
